/* eslint-disable require-jsdoc-except/require-jsdoc */
import { Rootstate } from '../redux/store';
import GameRule from './enum/game';
import { createSlice, PayloadAction } from '@reduxjs/toolkit';

interface GameState {
    /** 当前游戏玩家 */
    currentPlayer: PlayerIdentity;
    /** 游戏是否结束判定 */
    ending: boolean;
    /** 游戏胜利者 */
    endingTar: PlayerTarget;
    /** 当前执行记忆步数 */
    executeStep: number;
    /** 当前执行记忆棋盘数据 */
    actionChecked: CheckedListData;
}

const initialState: GameState = {
    currentPlayer: 0,
    ending: false,
    endingTar: null,
    executeStep: 0,
    actionChecked: Array(GameRule.MESH_COUNT).fill(null),
};

const gameStateSlice = createSlice({
    name: 'game',
    initialState,
    reducers: {
        changePlayer: (state) => {
            state.currentPlayer = state.currentPlayer ? 0 : 1;
        },
        clickAction: (state, action: PayloadAction<number>) => {
            state.currentPlayer = action.payload % 2 === 0 ? 0 : 1;
        },
        changeEndingState: (state, action: PayloadAction<{ending: boolean, endingTar?: PlayerTarget}>) => {
            state = Object.assign(state, action.payload);
        },
        setActionChecked: (state, action: PayloadAction<CheckedListData>) => {
            state.actionChecked = action.payload;
        },
        changeExecute: (state, action: PayloadAction<number>) => {
            state.executeStep = action.payload;
        },
    },
});

export const { changePlayer, changeExecute, changeEndingState, clickAction, setActionChecked } = gameStateSlice.actions;

export const selectGameState = (state: Rootstate) => state.gameState;
export default gameStateSlice.reducer;
